﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using CAOS.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace CAOS.Context
{
    public class CAOSContext : DbContext
    {
        public DbSet<Sistema> Sistemas { get; set; }
        public DbSet<Usuario> Usuarios { get; set; }
        public DbSet<Papel> Papeis { get; set; }
        public DbSet<Recurso> Recursos { get; set; }
        public DbSet<TrilhaAuditoria> Logs { get; set; }

        public CAOSContext()
        {
            //string script = ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();            
            //Database.SetInitializer(new SeedInitializer());
           // Database.SetInitializer(new MigrateDatabaseToLatestVersion<CAOSContext, Migrations.Configuration>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

            modelBuilder.Entity<Sistema>().HasMany(s => s.Papeis);

            modelBuilder.Entity<Recurso>().HasMany(r => r.RecursosFilhos)
                                          .WithOptional(r => r.RecursoPai)
                                          .HasForeignKey(r => r.RecursoPaiID);

            modelBuilder.Entity<Usuario>().HasMany(s => s.Papeis)
                                          .WithMany(p => p.Usuarios)
                                          .Map(x =>
                                          {
                                              x.MapLeftKey("USUA_SQ_USUARIO");
                                              x.MapRightKey("PAPE_SQ_PAPEL");
                                              x.ToTable("PAPEL_USUARIO");
                                          });

            modelBuilder.Entity<Papel>().HasMany(r => r.RecursosPermitidos)
                                        .WithMany()
                                        .Map(x =>
                                        {
                                            x.MapLeftKey("PAPE_SQ_PAPEL");
                                            x.MapRightKey("RECU_SQ_RECURSO");
                                            x.ToTable("PAPEL_RECURSO");
                                        });

            //modelBuilder.Entity<Sistema>()
            //.HasMany(s => s.Papeis)
            //.WithMany(t => t.Mayors)
            //.Map(x =>
            //{
            //    x.MapLeftKey("UserId");
            //    x.MapRightKey("TownId");
            //    x.ToTable("TownMayors");
            //});

            base.OnModelCreating(modelBuilder);
        }
    }

    internal class SeedInitializer : DropCreateDatabaseAlways<CAOSContext>
    {
        protected override void Seed(CAOSContext context)
        {
            Sistema sistema = new Sistema() { Sigla = "CAOS", Nome = "Controle de acesso", CodigoAutenticacao = "1234" };
            context.Sistemas.Add(sistema);

            Usuario usuario = new Usuario() { Nome = "Felipe", Login = "Felipe", Senha = "1234", Email = "felipe@felipe.com", Papeis = new List<Papel>(), IsAdministradorCAOS = true };
            context.Usuarios.Add(usuario);

            Papel papel = new Papel() { Sistema = sistema, IsPapelGestor = true, Nome = "Administrador" };
            context.Papeis.Add(papel);

            usuario.Papeis.Add(papel);

            context.SaveChanges();

            base.Seed(context);
        }
    }
}
